package net.hn.hnms.biz.common.activiti.config;

import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.ActivitiEngineAgenda;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityManager;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;

import java.util.List;

/**
 * 跳转到指定节点代码
 *
 * @author linyb-geek
 */
public class Jump2TargetFlowNodeCommand implements Command<Void> {
    private List<String> taskIds;

    private String targetFlowNodeId;

    private final String executionId;

    public Jump2TargetFlowNodeCommand(List<String> taskIds, String targetFlowNodeId, String executionId) {
        super();
        this.taskIds = taskIds;
        this.targetFlowNodeId = targetFlowNodeId;
        this.executionId = executionId;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
        TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();

        ExecutionEntity executionEntity = executionEntityManager.findById(executionId);
        Process process = ProcessDefinitionUtil.getProcess(executionEntity.getProcessDefinitionId());
        // 获取当前任务的来源任务及来源节点信息
        for (String taskId : taskIds) {
            TaskEntity taskEntity = taskEntityManager.findById(taskId);
            // 删除当前节点
            taskEntityManager.deleteTask(taskEntity, "", true, true);
        }
        // 获取要跳转的目标节点
        FlowElement targetFlowElement = process.getFlowElement(targetFlowNodeId);
        executionEntity.setCurrentFlowElement(targetFlowElement);
        ActivitiEngineAgenda agenda = commandContext.getAgenda();
        agenda.planContinueProcessInCompensation(executionEntity);

        return null;
    }

    public List<String> getTaskIds() {
        return taskIds;
    }

    public void setTaskIds(List<String> taskIds) {
        this.taskIds = taskIds;
    }

    public String getTargetFlowNodeId() {
        return targetFlowNodeId;
    }

    public void setTargetFlowNodeId(String targetFlowNodeId) {
        this.targetFlowNodeId = targetFlowNodeId;
    }

}